#include "function_s.h"
#include "pthreadpool.h"
#include <func.h>

int exitpipe[2];

void handler_signal(int signum){
    printf("start signal handle\n");
    char ch= 1 ;
    write(exitpipe[1],&ch,1);
} 

int main(int argc,char* argv[])
{   //server ip port
    signal(SIGPIPE,SIG_IGN);
    signal(SIGUSR1,handler_signal);
    pipe(exitpipe);
    ERROR1(argc,3);
    int port=atoi(argv[2]);
    char* ip=argv[1];
    pid_t pid=fork();
    if(pid>0){    
        printf("pid %d parent process has create!\n",getpid());
        close(exitpipe[0]);
        wait(NULL);
        exit(0);
    }
    close(exitpipe[1]);
    int listenfd=create_connect(port,ip);
    int efd=create_epoll(listenfd);
    struct epoll_event* list_event=(struct epoll_event*)calloc(MAX_NUM,sizeof(struct epoll_event));
    add_r_epoll(efd,exitpipe[0]);
    pthreadpool_t pool;
    pthreadpool_creat(&pool);
    pthreadpool_start(&pool);
    while(1){
        int num=epoll_wait(efd,list_event,MAX_NUM,-1);
        if(num==0){
            printf("out of time!\n");
        }
        else if(num==-1&&errno==EINTR){
            continue;
        }else if(num==-1&&errno!=EINTR){
            perror("epoll_wait");
            exit(1);
        }else{
            for(int i=0;i<num;i++){
                int sfd=list_event[i].data.fd;
                if(sfd==listenfd){
                    int newfd=accept(listenfd,NULL,NULL);
                    printf("client %d has connect!\n",newfd);
                    enqueue(&pool.queue,newfd);
                }
                else if(sfd==exitpipe[0]){
                    char ch;
                    read(sfd,&ch,1);
                    printf("pthread start quit!\n");
                    wakeupqueue(&pool.queue);
                    for(int j=0;j<PTHREAD_NUM;j++){
                        pthread_join(pool.index[j],NULL);
                    }
                    printf("pthread has quited!\n");
                    pthreadpool_destroy(&pool);
                    close(listenfd);
                    free(list_event);
                    close(efd);
                    exit(0);
                }
            }
        }
    }
}
